﻿using System;
using PmfWeb.Core.Cache;
using PmfWeb.Core.Web;

namespace PmfWeb.Core.Forms
{
    /// <summary>
    /// 缓存助手类
    /// </summary>
    public static class CacheHelper
    {
        /// <summary>
        /// 缓存是否存在
        /// </summary>
        /// <typeparam name="T">缓存的对象类型</typeparam>
        /// <param name="obj">返回的对象类型</param>
        /// <returns>是否存在该缓存,存在的话返回缓存值</returns>
        public delegate bool IsExits<T>(out T obj);

        /// <summary>
        /// 获取缓存的值
        /// </summary>
        /// <typeparam name="T">缓存的对象类型</typeparam>
        /// <returns>返回缓存对象</returns>
        public delegate T Getter<T>();

        ///<summary>
        ///</summary>
        ///<param name="obj"></param>
        ///<typeparam name="T"></typeparam>
        public delegate void Actions<T>(T obj);

        ///<summary>
        /// 获取缓存
        ///</summary>
        ///<param name="isExits">是否存在</param>
        ///<param name="source"></param>
        ///<param name="actions"></param>
        ///<typeparam name="T"></typeparam>
        ///<returns></returns>
        public static T Get<T>(IsExits<T> isExits, Getter<T> source,Actions<T> actions)
        {
            T obj;
            if (isExits(out obj)) return obj;
            obj = source();
            actions(obj);
            return obj;
        }

        ///<summary>
        /// 获取缓存的对象
        ///</summary>
        ///<param name="cacheKey">缓存Key</param>
        ///<param name="getter">获取的方法</param>
        ///<typeparam name="T">缓存对象类型</typeparam>
        ///<returns>缓存对象</returns>
        public static T Get<T>(string cacheKey,Getter<T> getter)
        {
            T obj;
            object data = Current.Context.Cache[cacheKey];
            if (null != data) return (T)data;
            //obj = (T)(Current.Context.Cache[cacheKey] ?? default(T));
            obj = getter();
            if (!System.String.IsNullOrEmpty(cacheKey)) Current.Context.Cache.Insert(cacheKey, obj, null, DateTime.Now, TimeSpan.Zero);
            return obj;
        }


    }
}
